package com.xxxx.server.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.RespBean;
import com.xxxx.server.service.IAdminService;
import com.xxxx.server.service.IOssService;
import com.xxxx.server.utils.Gitee.GiteeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  个人中心
 * </p>
 *
 * @author mi-nuo-ji
 * @since 1.0.0
 */
@Slf4j
@RestController
@Api(value = "个人中心",tags = "个人中心")
public class AdminInfoController {
    @Autowired
    private IAdminService adminService;
    @Autowired
    private IOssService ossService;

    @Value("${gitee.giteeAccessToken}")
    private String giteeAccessToken;

    @Value("${gitee.giteeOwner}")
    private String giteeOwner;

    @Value("${gitee.giteeRepoName}")
    private String giteeRepoName;


    @ApiOperation(value = "更新当前用户信息")
    @PutMapping("/admin-info")
    // Authentication 这个对象是 Security 提供的可以用他直接获取到当前登录用户的信息，Admin 是前端用户传过来的用户信息
    public RespBean updateAdmin(@RequestBody Admin admin, Authentication authentication){
        if (adminService.updateById(admin)){//只是跟新了数据库
            //更新用户的全局上下文信息
            SecurityContextHolder.getContext().setAuthentication(
                    new UsernamePasswordAuthenticationToken(admin, null, authentication.getAuthorities()));
            return RespBean.success("更新成功！");
        }
        return RespBean.error("更新失败!");
    }

    @ApiOperation(value = "更新用户密码")
    @PutMapping("/admin-pass")
    public RespBean updateAdminPassWord(@RequestBody Map<String,Object> info){
        //旧密码
        String oldPass = (String) info.get("oldPass");
        //新密码
        String pass = (String) info.get("pass");
        //当前登录用户ID
        Integer adminId = (Integer) info.get("adminId");
        return adminService.updateAdminPassWord(oldPass,pass,adminId);
    }

    /**
     * 上传图片
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/upload_image")
    @ResponseBody
    public RespBean uploadImg(@RequestParam("file") MultipartFile file) throws Exception {
        log.info("请求成功");
        String originaFileName = file.getOriginalFilename();
        //上传图片不存在时
        if(originaFileName == null){
            return RespBean.error("找不到图片！！！");
        }
        JSONObject jsonObject = new GiteeUtil(giteeAccessToken,giteeOwner,giteeRepoName).addFile("/common",file);
        //表示操作失败
        if (jsonObject==null || jsonObject.getObj("commit") == null) {
            return RespBean.error("上传失败！！！");
        }
        JSONObject content = JSONUtil.parseObj(jsonObject.getObj("content"));
        return RespBean.success("更新成功！", content.getObj("download_url"));
    }
    /**
     * 上传头像
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/admin/userface")
    @ApiOperation(value = "更新用户头像")
    @ResponseBody
    public RespBean uploadImg(MultipartFile file,
                                        Integer id,
                                        Authentication authentication) throws Exception {
        log.info("请求成功");
        String originaFileName = file.getOriginalFilename();
        //上传图片不存在时
        if(originaFileName == null){
            return RespBean.error("找不到图片！！！");
        }
//        JSONObject jsonObject = new GiteeUtil(giteeAccessToken,giteeOwner,giteeRepoName).addFile("/common/userface",file);
//        //表示操作失败
//        if (jsonObject==null || jsonObject.getObj("commit") == null) {
//            return RespBean.error("上传失败！！！");
//        }
//        JSONObject content = JSONUtil.parseObj(jsonObject.getObj("content"));
//        String url = (String) content.getObj("download_url");
        String url = ossService.uploadFileAvatar(file, "common/userface/"); //阿里云 oss
        return adminService.updateAdminUserFace(url,id,authentication);
    }



//    //这个功能需要自己找到包以后再用，详情请看pom.xml
//    @ApiOperation(value = "更新用户头像")
//    @PostMapping("/admin/userface")
//    public RespBean updateAdminUserFace(MultipartFile file,
//                                        Integer id,
//                                        Authentication authentication){
//        //上传之后的文件名
//        String[] filePath = FastDFSUtils.upload(file);
//        //获取 url ， 初始文件名，上传之后的文件名
//        String url = FastDFSUtils.getTrackerUrl() + filePath[0] + "/" + filePath[1];
//        return iAdminService.updateAdminUserFace(url,id,authentication);
//    }
}
